/*
 * This file is based on the libopencm3 project.
 *
 * Copyright (C) 2016 Nucleron R&D LLC (main@nucleron.ru)
 *
 * This library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */

/* STM32 example
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>

#include <libopencm3/cm3/cortex.h>
#include <libopencm3/cm3/nvic.h>
*/

#include <plc_dbg.h>
#include <plc_config.h>
#ifdef MONITOR_NET
#include <STM32Ethernet.h>
#include <EthernetServer.h>
EthernetServer server(8080);
EthernetClient client;
#endif
void dbg_serial_init(void)
{
    Serial1.begin(115200);
#ifdef LWIP
#ifdef MONITOR_NET
    server.begin();
#endif
#endif
}

int dbg_serial_write(unsigned char *d, unsigned short n)
{
    int res = 0;
#ifdef LWIP
#ifdef MONITOR_NET
    if (client.connected())
    {
        client.write(d, n);
    }
#endif
#endif

    res = Serial1.write(d, n);
    return res;
}

int dbg_serial_read(unsigned char *d, unsigned short n)
{
    int res;
    res = 0;
    if (Serial1.available() >= n)
    {
        res = Serial1.readBytes(d, n);
        return res;
    }
#ifdef LWIP
#ifdef MONITOR_NET
    client = server.available();
    if (client)
    {
        if (client.connected())
        {
            if (client.available())
            {
                res = client.read(d, n);
                return res;
            }
        }
    }
#endif

#endif
    return res;
}
